<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

final class Recept extends BIT_Model
{
	public static $class_name = __CLASS__;
	
	protected $id;
	
	protected $namn;
	
	protected $ravara;
	
	protected $huvud_ingrediens;

	protected $ingredienser;
	
	protected $typ;

	protected $tid;

	protected $onske;

	protected $tillagning;

	protected $personer;

	protected $copyright;
	
	private $db = "";
	
	function __construct(){
		parent::__construct();
	}
	
	public static function getRecipeList($pagesize = 5, $page = 1){
		$db = get_instance()->db;
		$from = ($page-1) * $pagesize;

		return $db->order_by('id' ,'desc')->limit($pagesize, $from)->get('recept')->result();
	}

	public function getProductRelatedRecipes( $ravara, $limit=999 ){
		$db = get_instance()->db;
		return $db->order_by('rating', 'desc')->where('ravara', $ravara)->limit($limit)->get('recept')->result();
	}

	public function getProductsInRecipe( $rec_id ){
		$db = get_instance()->db;
		return $db->order_by('namn','desc')
				  ->join('produkter','produkter.id = produkter_recept.produkt_id')
				  ->where('recept_id', $rec_id)
				  ->get('produkter_recept')
				  ->result();
	}

	public function count(){
		$db = get_instance()->db;
		return count( $db->query("SELECT ID FROM recept")->result());
	}

	public function get_json_recipes(){
		$db = get_instance()->db;
		return $db->query("SELECT slug AS value, namn AS label FROM recept ORDER BY namn ASC")->result();
	}

	public function getRecipe( $id ){
		$db = get_instance()->db;

		// Get by id?
		if( is_int( $id )){
			$result = $db->where('id',$id)->limit(1)->get('recept')->result();
		}
		// Get by slug?
		else {
			$result = $db->where('slug',$id)->limit(1)->get('recept')->result();
		}
		
		// Return first element or false
		if(count( $result ) > 0)
			return $result[0];
		
		else return 
			false;
	}
}